#include "StrmBMP_reader.h"

StrmBMP_reader::StrmBMP_reader(const std::string& filePath) : file(filePath,std::ios::binary)
{
  if(!file.is_open())
    throw std::logic_error("无法打开文件");
  file.seekg(0,std::ios::beg);
  file.read((char*)&fileHead_,sizeof(fileHead));
}

StrmBMP_reader::~StrmBMP_reader()
{
  if(file.is_open())
    file.close();
}

fileHead StrmBMP_reader::GetFileHead()
{
  return fileHead_;
}

long StrmBMP_reader::GetImageSize()
{
  return fileHead_.imageDataBlockLength/(sizeof(imageBlockHead)+fileHead_.imageWidth*fileHead_.imageHeight);
}

void StrmBMP_reader::BeginReadBMP()
{
  file.seekg(2048,std::ios::beg);
}

std::pair<imageBlockHead,char*> StrmBMP_reader::GetImageFrame()
{
  if(file.tellg()>=fileHead_.imageDataBlockLength+2048)
    return {{0,0},nullptr};
  imageBlockHead BlockHead;
  char* imageData=new char[fileHead_.imageHeight*fileHead_.imageWidth*fileHead_.pixelType];
  file.read((char*)&BlockHead,sizeof(imageBlockHead));
  file.read(imageData,fileHead_.imageHeight*fileHead_.imageWidth*fileHead_.pixelType);
  if(!file.good())
  {
    delete [] imageData;
    imageData=nullptr;
  }
  return {BlockHead,imageData};
}

void StrmBMP_reader::BeginReadAdditional()
{
  file.seekg(2048+fileHead_.imageDataBlockLength,std::ios::beg);
}

additionalBlockHead StrmBMP_reader::GetAdditionalFrame()
{
  additionalBlockHead BlockHead;
  file.read((char*)&BlockHead,sizeof(additionalBlockHead));
  if(!file.good())
    throw std::exception();
  return BlockHead;
}

